package com.sixuan.rabbitmqconsumer.workmode.publishandsubscribe;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * RabbitMq工作模式：publish/subscribe模式（发布订阅模式）
 * 1.一个生产者将消息发送给交换机；
 * 2.交换机绑定了多个队列，每个队列绑定了自己对应的消费者（不止一个，多个的话，这几个消费者达成WorkQueues模式）；
 * 3.生产者将消息发送给交换机，交换机转发消息到与其绑定的队列上，交换机的每个队列都会收到这个消息。
 * Created by LENOVO on 2020-7-8 17:18
 *
 * @author LENOVO
 */
public class EmailConsumer {

    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String EMAIL_QUEUE_INFORMATION = "email_queue_information";
    private static final String EXCHANGE_FANOUT_INFORMATION = "exchange_fanout_information";

    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_FANOUT_INFORMATION, BuiltinExchangeType.FANOUT);
        //声明队列
        channel.queueDeclare(EMAIL_QUEUE_INFORMATION, true, false, false, null);
        //将队列绑定到交换机上
        channel.queueBind(EMAIL_QUEUE_INFORMATION, EXCHANGE_FANOUT_INFORMATION, "");
        //接收到消息后的执行方法
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //交换机
                String exchange = envelope.getExchange();
                long deliveryTag = envelope.getDeliveryTag();
                String message = new String(body, "utf-8");
                System.out.println("Received from provider : " + message);
            }
        };
        //监听消息basicConsume
        channel.basicConsume(EMAIL_QUEUE_INFORMATION, true, defaultConsumer);
    }
}
